package Design_patterns.creator_mode.singleton.demo9;


import java.io.*;

/**
 * @description: 测试使用序列化反序列化破坏单例模式（解决方案）
 **/

public class Client {
    private static final String FILEPATH = "C:\\Users\\10322\\Desktop\\a.txt";

    public static void main(String[] args) {
        writeObject2File();
        readObjectFromFile();
        readObjectFromFile();
        /*
        结果
            instance = Design_patterns.creator_mode.singleton.demo9.Singleton@3764951d
            instance = Design_patterns.creator_mode.singleton.demo9.Singleton@3764951d
         */

    }

    //从文件中读数据（对象）
    public static void readObjectFromFile() {
        try {
            //1.创建对象输入流对象
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILEPATH));

            //2.读取对象
            Singleton instance = (Singleton) ois.readObject();

            System.out.println("instance = " + instance);
            //3.释放资源
            ois.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    //向文件中写数据（对象）
    public static void writeObject2File() {
        //1.获取Singleton对象
        Singleton instance = Singleton.getInstance();
        try {
            //2.创建对象输出流对象
            ObjectOutputStream oos =
                    new ObjectOutputStream(new FileOutputStream(FILEPATH));

            //3.写对象
            oos.writeObject(instance);
            //4.释放资源
            oos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
